<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <!--

            简写: 一般常见于 单个数据传参
            this.$router.push('/import?type=user')

            完整写法: 多个数据传递
            this.$router.push({
              path: '/import',
              query: {
                type: 'user',
                xx: xx
              }
            })
           -->
          <el-button v-if="checkBtnAccess('POINT_EXCEL_IMPORT')" type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button v-if="checkBtnAccess('POINT_EXCEL_EXPORT')" type="danger" size="small" @click="handleExportExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="handleAddEmployee">新增员工</el-button>
        </template>
      </PageTools>

      <el-card v-loading="loading" style="margin-top: 10px;">
        <el-table :data="list" border>
          <el-table-column label="序号" type="index" :index="indexMethod" sortable width="100" />
          <el-table-column label="头像" sortable>
            <template #default="{ row }">
              <img
                v-imgerror="errorImg"
                class="staff-photo"
                :src="row.staffPhoto || defaultPhoto"
                alt=""
                @click="handleImgClick(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable />
          <el-table-column label="手机号" prop="mobile" sortable />
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column :formatter="formatEmploy" label="聘用形式" prop="formOfEmployment" sortable />
          <el-table-column label="部门" prop="departmentName" sortable />
          <el-table-column label="入职时间" sortable>
            <template #default="{ row }">
              {{ row.timeOfEntry | formatTime('YYYY年MM月DD日') }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                :disabled="!checkBtnAccess('POINT_USER_EDIT')"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="handleClickRole(row.id)">角色</el-button>
              <el-button :disabled="!checkBtnAccess('POINT_USER_DELETE')" type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[1,2,3,4,5,6,7,8,9,10]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </el-card>

      <AddEmployee
        :show-dialog.sync="isShow"
        @add-employee="getUserList"
      />
      <!-- <AddEmployee
        :show-dialog.sync="isShow"
      /> -->

      <el-dialog
        width="400px"
        title="二维码预览"
        :visible="show2WeiCode"
        @close="show2WeiCode = false"
      >

        <!-- 二维码 必须 放在canvas html5原生标签: 画布(你画我猜) 绘制复杂图像 -->
        <!-- ref 获取dom / 组件 -->
        <div style="text-align: center">
          <canvas ref="myCanvas" />
        </div>
      </el-dialog>

      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { reqDelEmployee, reqGetUserList } from '@/api/employees'
import AddEmployee from './components/AddEmployee.vue'
import obj from '@/constant/employees'
import dayjs from 'dayjs'
import errorImg from '@/assets/common/bigUserHeader.png'
// 装包 => 导包 => 调用方法
import QrCode from 'qrcode'
import AssignRole from './components/AssignRole.vue'
import hello from '@/mixins/hello'
import check from '@/mixins/check'

// vue中默认开启一个严格模式 strict : 全局作用域下 this => undefined
// console.log(this, 8989)

// function a() {
//   console.log(this, 7878)
// }
// a()

export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  mixins: [hello, check],
  data() {
    return {
      page: 1,
      pagesize: 5,
      list: [],
      total: 0,
      loading: false,
      isShow: false,
      defaultPhoto: 'https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2146034403,1504718527&fm=26&gp=0.jpg',
      errorImg,
      show2WeiCode: false,
      showRoleDialog: false,
      userId: '' // 用于存储点击了哪个用户
    }
  },
  created() {
    this.getUserList()
    // console.log('大家好, 我是一个页面组件')
  },
  methods: {
    handleAddEmployee() {
      if (!this.checkBtnAccess('POINT_USER_ADD')) {
        this.$message.error('请联系管理员, 添加权限')
        return
      }

      this.isShow = true
    },
    // 获取最新数据, 渲染
    async getUserList() {
      this.loading = true
      const { data: { rows, total }} = await reqGetUserList(this.page, this.pagesize)
      // console.log(res)
      this.list = rows
      this.total = total
      this.loading = false
    },
    handleCurrentChange(val) {
      // val 页码
      this.page = val
      this.getUserList()

      // 普通函数下 this => 当前组件实例 => this.page this.getUserList
      // 箭头函数 () => {}  => this指向父级作用域中的this => this=> 全局作用域
    },
    // xxx: () => {
    //   console.log(this)
    // },
    handleSizeChange(val) {
      // val 用户自己选择的每页条数
      this.pagesize = val

      // 回到第一页
      this.page = 1

      // 获取数据
      this.getUserList()
    },
    indexMethod(index) {
      // index 从0开始
      return index + 1 + this.pagesize * (this.page - 1)
    },
    formatEmploy(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // row 每一行的数据
      // column 列的相关信息
      // cellValue  单元格本来的数据
      // index 下标
      // return cellValue === 1 ? '正式工' : '临时工'
      // return 'hahah'
      const arr = obj.hireType
      const res = arr.find(item => item.id === +cellValue)
      return res ? res.value : '未知'
    },
    del(id) {
      // 让用户确认
      this.$confirm('该操作将永久删除该员工, 不可逆,你确定继续么?', '温馨提示').then(async() => {
        // 发送请求
        const res = await reqDelEmployee(id)
        console.log(res)
        // 提示用户
        this.$message.success('删除员工成功!!!')

        // 如果这个是最后一条数据 且 页码 > 1
        if (this.list.length === 1 && this.page > 1) {
          // 回到上一页
          this.page--
        }

        // 获取新数据
        this.getUserList()
      }).catch(() => {
        console.log('取消')
      })
    },
    async handleExportExcel() {
      // 表头
      //                 ['姓名', '主要信息', '     ', '      ', '      ', '    ', '部门']
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      // 中英文对照表
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }

      // 原数据 => [{}, {}, {}, ...]
      const { data: { rows }} = await reqGetUserList(1, this.total)
      console.log(rows)

      // 多表头
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']

      const result = this.transOriginTo2Wei(rows, headersArr, headersRelations)
      // console.log(result, 5678)

      import('@/vendor/Export2Excel').then(excel => {
        console.log(excel)

        // [1,2,3]
        // [{}, {}, {}]
        // [[], [], [], ...]

        // ['姓名', '学号', '年纪', '描述']

        excel.export_json_to_excel({
          // 表格的头部 数组(有序)
          header: headersArr,
          // 表格的主体数据 固定格式 => 二维数组
          // 外面为什么是数组: 熊大 熊二 是需要顺序
          // 内层为什么是数组? 熊大的每条数据也都是都有顺序的!!!
          data: result,
          filename: '员工信息表',
          autoWidth: true, // 非必填
          bookType: 'xlsx', // 非必填
          multiHeader,
          merges
        })
      })
    },
    transOriginTo2Wei(rows, headersArr, headersRelations) {
      // ...一顿处理 => 二维数组
      // 外层数组的长度 => 有多少个小数组 => rows里面有多少条数据决定了有多少个小数组
      // 内层数组的长度 => headersArr里面有多少个数据 决定了 小数组里面有几条数据
      const arr = []
      // [[],[],[]]

      rows.forEach(item => {
        const res = []

        headersArr.forEach(v => {
          const englishKey = headersRelations[v]
          let val = item[englishKey]
          // val = 1 2 3
          if (englishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resObj = hireType.find(item => item.id === +val)
            val = resObj ? resObj.value : '未知'
          }
          // val 2018-09-11 2019-01-02
          if (['timeOfEntry', 'correctionTime'].includes(englishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          res.push(val)
        })

        arr.push(res)
      })

      return arr
    },
    handleImgClick(url) {
      if (!url) return
      // 显示对话框
      // dom异步更新!!!
      this.show2WeiCode = true

      this.$nextTick(() => {
        // QrCode.toCanvas(放二维码的容器, 携带的信息)
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    handleClickRole(id) {
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff-photo {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}

</style>
